﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SaveMeGUI;
using System.Collections;
using System.Net;
using System.Timers;
using System.Threading;


namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        delegate void SetDataGridView();
        delegate void SetSomething();
        private Thread demoThread;
        private Thread demoThread2;
        private readonly String statusCase1 = "No taxi assigned";
        private readonly String statusCase2 = "Taxi on the way";
        private readonly String statusCase3 = "Taxi arrived";
        private readonly String statusCase4 = "Canceled";

        private readonly String buttonCase0 = "Put Plates and Time";
        private readonly String buttonCase1 = "Send taxi";
        private readonly String buttonCase2 = "Announce taxi arrival";
        private readonly String buttonCase3 = "Remove";
 

        public Form1()
        {
            InitializeComponent();            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            displayTaxiOrders();
        }

        private void ProcSafe()
        {
            this.AddRows();
        }

        private void AddRows()
        {

            if (this.dataGridView1.InvokeRequired)
            {
                SetSomething d = new SetSomething(AddRows);
                this.Invoke(d);
            }

            else
            {
                try
                {
                    XMLParser parser = new XMLParser();
                    List<string[]> listRequests = new List<string[]>();
                    listRequests = parser.GetRequests();
                    int i = 0;
                    if (listRequests != null)
                    {
                        foreach (string[] str in listRequests)
                        {
                            dataGridView1.Rows.Add(str);

                            if (dataGridView1["Status", i].Value == statusCase1)
                            {
                                dataGridView1["Action", i].Value = buttonCase0;
                           
                            }

                            if (dataGridView1["Status", i].Value == statusCase2)
                            {
                                dataGridView1["Action", i].Value = buttonCase2;
                            }

                            if (dataGridView1["Status", i].Value == statusCase4)
                            {
                                dataGridView1["Action", i].Value = buttonCase3;
                            }

                            i++;
                        }
                    }
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine("We got an error with empty lists: " + e.Message);
                }
            }

        }

        private void ThreadProcSafe()
        {
            this.Clear();
        }

        private void Clear()
        {

            if (this.dataGridView1.InvokeRequired)
            {
                SetDataGridView d = new SetDataGridView(Clear);
                this.Invoke(d);
            }
            else
            {
                dataGridView1.Rows.Clear();
            }
        }


        private void displayTaxiOrders()
        {
            this.demoThread =
            new Thread(new ThreadStart(this.ThreadProcSafe));

            this.demoThread.Start();


            this.demoThread2 =
                new Thread(new ThreadStart(this.ProcSafe));

            this.demoThread2.Start();

        }

        private void removeCanceled(string id) {
            string url_id = "http://balder.ucn.dk/dm77_gr2/SaveMe.svc/MarkCancelRequestAsReviewed/" + id;
            HttpWebRequest request_id = (HttpWebRequest)WebRequest.Create(url_id);
            HttpWebResponse response_id = (HttpWebResponse)request_id.GetResponse();
        }

        private void wcfSaveInfo(string id, string platenumber, string timeEstimate)
        {

            if (string.IsNullOrEmpty(timeEstimate))
            {
                timeEstimate = "-";
            }

            if (string.IsNullOrEmpty(platenumber))
            {
                platenumber = "-";
            }

            string url_id = "http://balder.ucn.dk/dm77_gr2/SaveMe.svc/UpdateTaxiRequest/" + id;
            HttpWebRequest request_id = (HttpWebRequest)WebRequest.Create(url_id);
            HttpWebResponse response_id = (HttpWebResponse)request_id.GetResponse();

            string url_time = "http://balder.ucn.dk/dm77_gr2/SaveMe.svc/UpdateTaxiRequestWithEstimatedTime/" + id + "-" + timeEstimate;
            HttpWebRequest request_time = (HttpWebRequest)WebRequest.Create(url_time);
            HttpWebResponse response_time = (HttpWebResponse)request_time.GetResponse();

            string url_plate = "http://balder.ucn.dk/dm77_gr2/SaveMe.svc/UpdateTaxiRequestWithPlateNumber/" + id + "-" + platenumber;
            HttpWebRequest request_plate = (HttpWebRequest)WebRequest.Create(url_plate);
            HttpWebResponse response_plate = (HttpWebResponse)request_plate.GetResponse();


        }

        void dataGridView1_CurrentCellDirtyStateChanged(object sender,
    EventArgs e)
        {
            if (dataGridView1.IsCurrentCellDirty)
            {
                dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            int rowIndex = e.RowIndex;

            //check if the change is after the initialization
            //and is not result of button pressed or status change 

            try
            {
                if (dataGridView1.ColumnCount>e.ColumnIndex && rowIndex != -1 && rowIndex < dataGridView1.RowCount && e.ColumnIndex != 7 && e.ColumnIndex != 8)
                {
                    if (dataGridView1["PlateNumber", rowIndex].Value.ToString().Length != 0 && dataGridView1["TimeRequest", rowIndex].Value.ToString().Length != 0)
                    {
                        dataGridView1["Action", rowIndex].Value = buttonCase1;
                    }
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                dataGridView1["Action", rowIndex].Value = buttonCase0;
            }
        }

 

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            int columnindex = dataGridView1.Columns["Action"].Index;
            if (e.ColumnIndex == columnindex)
            {
                try
                {

                    int rowIndex = e.RowIndex;
                    String currentStatus = dataGridView1["Status", rowIndex].Value as String;
                    String currentButton = dataGridView1["Action", rowIndex].Value as String;


                    if (currentStatus.Equals(statusCase1) && dataGridView1["PlateNumber", rowIndex].Value.ToString().Length != 0 && dataGridView1["TimeRequest", rowIndex].Value.ToString().Length != 0)
                    {
                        wcfSaveInfo(dataGridView1["ID", rowIndex].Value as String, dataGridView1["PlateNumber", rowIndex].Value as String, dataGridView1["TimeRequest", rowIndex].Value as String);

                        dataGridView1["Status", rowIndex].Value = statusCase2;
                        dataGridView1["Action", rowIndex].Value = buttonCase2;

                    }
       
                    else if (currentStatus.Equals(statusCase2))
                    {
                        wcfSaveInfo(dataGridView1["ID", rowIndex].Value as String, dataGridView1["PlateNumber", rowIndex].Value as String, dataGridView1["TimeRequest", rowIndex].Value as String);

                        dataGridView1["Status", rowIndex].Value = statusCase3;
                        dataGridView1["Action", rowIndex].Value = "Proceed to next order";
                    }

                    else if (currentStatus.Equals(statusCase4))
                    {
                        removeCanceled(dataGridView1["ID", rowIndex].Value as String);
                        dataGridView1.Rows.RemoveAt(rowIndex);
                    }

                    else if (currentButton.Equals("Proceed to next order"))
                    {
                        dataGridView1.Rows.RemoveAt(rowIndex);
                    }
                }

                catch (Exception ex) {
                    System.Diagnostics.Debug.WriteLine("We got an error with empty lists: " + ex.Message);
                }
            }
        }

        private void menuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            displayTaxiOrders();
        }

        private void aboutToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Maecrosoft \n" + " \n" + "List of Credits:\n" + "\n" + "Dan-Ionuț Coconețu \n" +
                "Domas Tartilas \n" + "Georgi Damyanov \n" + "Paulius Gudonis \n" + "Patriciu Victor \n" + "Pop Roland \n");

        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == (Keys.F5))
            {
                displayTaxiOrders();
                return true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }


    }
}
